import { type ApiListItem, getList } from '@/api/api-manage/list'
import { usePagination } from '@/hooks/usePagination'
import { omitEmptyValue } from '@/utils/common'
import { assign } from 'lodash-es'

export default function useApiList() {
  const searchParams = reactive({
    apiName: null,
    sortBy: 2,
    apiCatalog: null,
    algorithmBasic: null,
    publishTimeType: 0,
    apiType: null,
    isMine: 'true',
  })
  const data = ref<Array<ApiListItem>>([])
  const [loading, toggleLoading] = useToggle()
  const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)

  async function onSearch() {
    toggleLoading(true)
    if (searchParams.apiType == null || searchParams.apiType == '') {
      searchParams.apiType = [1, 2, 3]
    }
    const { rows, total } = await getList(
      omitEmptyValue(assign({}, toRaw(searchParams), paginationParams.value))
    ).finally(() => {
      toggleLoading(false)
    })
    data.value = rows
    pagination.total = total
  }

  return { data, searchParams, loading, pagination, changePageNumber, changePageSize, onSearch }
}
